# -*- coding: utf-8 -*-
# @Author  : 楼炎锋
# @Email   : louyf23357@hundsum.com
# @Time    : 2019/5/30 21:25
# @File    : CrkPublic.py
import ctypes
import time
from Lib import Common
from Lib.ClassSelenium import ClassSelenium
from selenium.webdriver.common.keys import Keys
from Lib.Log import logger
from Lib.Common import setFail
from time import sleep
import re
'''
登录方法
@username:用户名
@password:密码
'''
def login(username, password):

    URL = 'http://192.168.44.86:8089/Artemis/mainframe/frame.html'
    global driver
    driver = ClassSelenium(URL, 'chrome')
    element = driver.getElementByAttribute('xpath://input[@name="username"]')
    element.send_keys(username)
    element = driver.getElementByAttribute('id:user_password')
    element.send_keys(password)
    element = driver.getElementByAttribute('id:login_submit')
    element.click()
    element = driver.getElementByAttribute('xpath://*[@id="content_tablist_frame_navigation_athena_dijit_TemplatePanel_index"]')
    logger.info("打开测试网址：" + URL)
    return driver

'''
搜索并且定位到菜单
@menuName:菜单名称，string格式
@elementObj:菜单标签的定位
'''
def getMenu(menuName, elementObj):

    # 定位到具体菜单
    element = driver.getElementByAttribute('xpath://*[@id="dijit_form_TextBox_0"]')
    element.clear()
    element.send_keys(menuName)
    sleep(1)
    element.send_keys(Keys.ENTER)
    sleep(2)
    logger.info('测试开始：定位到【%s】菜单' % menuName)
    element = driver.getElementByAttribute(elementObj)
    sleep(3)
    element.click()
    sleep(5)


'''
关闭浏览器
@menuName:菜单名称，string格式
'''
def close(menuName):

    driver.close()
    logger.info('关闭【%s】测试窗口 '% menuName)


'''
搜索框查询数据
@queryBoxElement:搜索输入框定位
@searchMessage：搜索的关键字
'''
def search(queryBoxElement, searchMessage):

    element = driver.getElementByAttribute(queryBoxElement)
    logger.info('测试【查询】功能')
    element.click()
    element.clear()
    element.send_keys(searchMessage)
    element.send_keys(Keys.ENTER)
    logger.info('点击“查询”')
    sleep(3)

'''
单击事件
@clickElement:需要点击的元素
@msg：点击元素的名称
'''
def click(clickElement, msg):

    element = driver.getElementByAttribute(clickElement)
    element.click()
    logger.info('点击‘%s’' % msg)
    sleep(0.5)



'''
输入框内写入
@clickElement:输入框定位
@msg：写入内容
'''
def write( element, msg):

    element = driver.getElementByAttribute(element)
    element.click()
    element.clear()
    element.send_keys(msg)
    element.send_keys(Keys.ENTER)
    logger.info('输入%s' % (msg))
    time.sleep(0.5)



'''
弹出框直接确定
'''
def confirm():
    # 弹出框确定

    driver.getAlert()
    logger.info("弹出框点击“确认”!")


'''
正则表达式匹配动态元素，生成xpath
@para：正则匹配的表达式
@msg:需要拼接的字段
@i:需要匹配的项目编号
@result:返回数据类型，默认为正则表达式匹配结果
'''
def reMatch(para,msg='',i=0,result='xpath'):

    html = driver.driver.page_source
    getResult = re.findall(para, html)[int(i)]
    if result=='xpath':
        getResult='xpath://*[@id='+getResult+']'+msg
    return getResult


'''
replace方法，替换元素
@str需要替换的元素
@text：需要用于替换的文本
@replaceStr被替换的问题
'''
def replaceNum(str,text,replaceStr='replace'):

    return str.replace(replaceStr,text)


'''
获取标签名称
@elementObj:标签对应元素定位
@tag：对应标签的名称
'''
def getTagText(elementObj,tag):

    msg = driver.getElementByAttribute(elementObj)
    sleep(0.5)
    msg = msg.getAttribute(tag)
    return msg



'''
获取元素对应文本内容
@elementObj：元素定位
'''
def getText(elementObj):
    #获取文本

    msg = driver.getElementByAttribute(elementObj)
    sleep(0.5)
    msg = msg.getgetAttributeText().strip().strip('\r\n').replace('\r\n',u'').replace(u'\u3000', u'').replace(u'\xa0', u'')
    return msg


def get_Attribute(elementObj,inputStr):
    #获取指定属性的值文本
    msg = driver.getElementByAttribute(elementObj)
    sleep(0.5)
    msg = msg.getAttribute(inputStr)

    return msg

'''
清空输入框
@elementObj：输入框元素定位
'''
def msgClear(elementObj):

    elementObj = driver.getElementByAttribute(elementObj)
    elementObj.clear()
    elementObj.send_keys(Keys.ENTER)
    logger.info('清除信息')
    time.sleep(0.5)



'''
返回复选框的选中状态，TRUE为选中，false为未选中
@clickElement:复选框定位
'''
def checkbox(clickElement):

    elementObj = driver.findElement(clickElement)
    elementObj = elementObj.is_selected()
    return elementObj



'''
测试导入功能
@uploadElement：上传元素定位
@uploadFile：上传文件路径
'''
def upload(uploadElement, uploadFile):

    elementObj= driver.findElement(uploadElement)
    elementObj.send_keys(uploadFile)
    time.sleep(1)
    logger.info('导入“附件”')
    time.sleep(2)


'''
设置断言
@elementObj1：期望元素定位
@elementObj2：断言元素定位
'''
def elementCheckElement(elementObj1,elementObj2):
    # 设置断言

    checkMsg1 = driver.getElementByAttribute(elementObj1)
    checkMsg1 = checkMsg1.getText().strip().strip('\r\n').replace('\r\n',u'').replace(u'\u3000', u'').replace(u'\xa0', u'')
    checkMsg2 = driver.getElementByAttribute(elementObj2)
    checkMsg2 = checkMsg2.getText().strip().strip('\r\n').replace('\r\n',u'').replace(u'\u3000', u'').replace(u'\xa0', u'')
    logger.info('期望信息为：%s' % checkMsg1)
    logger.info('断言信息为：%s' % checkMsg2)
    time.sleep(1)
    if checkMsg1 == str(checkMsg2):
        msg = "断言成功"
        logger.info('断言结果为：%s' % msg)
    else:
        msg = "断言失败！"
        driver.getScreen()
        setFail("断言失败！")
        logger.error('断言结果为：%s' % msg)
        driver.close()
        exit()



'''
设置断言
@rightMsg：期望文本值
@elementObj：断言元素定位
'''
def msgCheckElement(rightMsg,elementObj ):
    # 设置断言

    checkMsg = driver.getElementByAttribute(elementObj)
    checkMsg = checkMsg.getText()
    logger.info('期望信息为：%s' % rightMsg)
    logger.info('断言信息为：%s' % checkMsg)
    time.sleep(1)
    if rightMsg == str(checkMsg):
        msg = "断言成功"
        logger.info('断言结果为：%s' % msg)
    else:
        msg = "断言失败！"
        driver.getScreen()
        setFail("断言失败！")
        logger.error('断言结果为：%s' % msg)
        driver.close()
        exit()


'''
判断传入的两个文本是不相等
@wantMsg:期望文本值
@getMsg:获取文本值
'''
def textCheckEqual(wantMsg,getMsg ):
    # 设置断言

    logger.info('期望信息为：%s' % wantMsg)
    logger.info('断言信息为：%s' % getMsg)
    time.sleep(1)
    if str(wantMsg) == str(getMsg):
        msg = "断言成功"
        logger.info('断言结果为：%s' % msg)
    else:
        msg = "断言失败！"
        driver.getScreen()
        setFail("断言失败！")
        logger.error('断言结果为：%s' % msg)
        driver.close()
        exit()



'''
判断传入的两个文本是否不相等
'''
def textCheckNotEqual(rightMsg,wantMsg):

    logger.info('期望信息为：%s' % rightMsg)
    logger.info('断言信息为：%s' % wantMsg)
    time.sleep(1)
    if rightMsg != str(wantMsg):
        msg = "断言成功"
        logger.info('断言结果为：%s' % msg)
    else:
        msg = "断言失败！"
        driver.getScreen()
        setFail("断言失败！")
        logger.error('断言结果为：%s' % msg)
        driver.close()
        exit()


'''
下拉框控件匹配多选
@clickElement：能够展开下拉框的元素定位
@controlElement：下拉框内所有元素标准表达式
@msgs：所要匹配下拉框内容(多条数据以英文，进行分割)
'''
def matchMethod(clickElement, controlElement,msgs):

    msgList=msgs.split(',')
    element = driver.getElementByAttribute(clickElement)
    element.click()
    elementList = driver.getElementByAttribute(controlElement, getAll=True)
    for msg in msgList:
        for element in elementList:
            if element.getText().strip().strip('\r\n').replace('\r\n',u'').replace(u'\u3000', u'').replace(u'\xa0', u'') == msg:
                time.sleep(0.5)
                element.click()
                logger.info('选中的内容为:%s' %msg)
                break



'''
双击元素
@element：需要双击的元素
'''
def doubleClick(element,msg):

    element = driver.getElementByAttribute(element)
    driver.doubleClick(element)
    logger.info('双击%s' % (msg))
    sleep(0.5)


'''
滑动滚动条将元素至于可见位置
@element：需要双击的元素
'''
def showElement(element):

    element=element.split(':')[1]
    target = driver.driver.find_element_by_xpath(element)  # 要聚焦的目标元素
    driver.driver.execute_script("arguments[0].scrollIntoView();", target)
    sleep(0.5)


'''
根据html元素title值获取对应xpath
@msg：title名称
'''
def titleXpath(msg):

    return 'xpath://li[@title="'+msg+'"]'

'''
动态拼接上传文件路径方法（一）（根据场景用例名称进行建立目录存放）
@uploadFile 上传文件名，带后缀形式，例如xxx.xls
'''
def UploadFileAcitve(uploadFile):
    return Common.UploadPathActive + uploadFile
'''
动态拼接上传文件路径 方法（二）(根据界面模块建立目录存放)
@uploadFile 上传文件名，带后缀形式，例如xxx.xls
'''
def UploadFileAcitveTow(uploadFile):
    return Common.UploadPathActiveTow+uploadFile
'''
@flag:传入Boolean值为True情况下为表示隐藏浏览器
'''
def isShowControlWindow(flag):
    if not (isinstance(flag, bool)):
        logger.error("控制台展示标志位类型错误")
        setFail("控制台展示标志位类型错误!")
        exit()
    if flag==False:
        whnd = ctypes.windll.kernel32.GetConsoleWindow()
        if whnd != 0:
            ctypes.windll.user32.ShowWindow(whnd, 0)
            ctypes.windll.kernel32.CloseHandle(whnd)
    elif flag==True:
        pass

def TbodySelect(clickElement, option='2'):
    '''
        评分卡内Select标签自动选择
        参数
            @clickElement：评分卡的表单xpath元素到tbody标签
            @option：下拉框索要选择的位置；            DefaultValue:默认选择第二个
        '''
    selectXpath = clickElement + '//select'
    selectXpath = driver.driver.find_elements_by_xpath(selectXpath)
    selectSubsetXpath = clickElement + '//select/child::option[' + option + ']'
    selectSubsetXpath = driver.driver.find_elements_by_xpath(selectSubsetXpath)
    x = 0
    for i in range(len(selectXpath)):
        try:
            a = selectXpath[i]
            a.click()
        except:
            continue
        else:
            for y in range(len(selectSubsetXpath)):
                try:
                    selectSubsetXpath[x].click()
                    x += 1
                    break
                except:
                    x += 1
                    continue

def TbodyTextarea(clickElement,textarea='11'):
    '''
        评分卡内textarea标签自动输入
        参数
            @clickElement：评分卡的表单xpath元素到tbody标签
            @textarea：textarea标签输入框输入的内容;   DefaultValue:任意文本值
        '''
    textareaXpath = clickElement + '//textarea'
    textareaXpath = driver.driver.find_elements_by_xpath(textareaXpath)
    for i in textareaXpath:
        try:
            i.clear()
            i.send_keys(textarea)
        except:
            continue
def TbodyInput(clickElement,input='11'):
    '''
        评分卡内input标签自动输入
        参数
            @clickElement：评分卡的表单xpath元素到tbody标签
            @input：input标签输入框输入的内容;         DefaultValue:任意文本值
        '''
    inputXpatch = clickElement + '//input'
    inputXpatch = clickElement + '//input'
    inputXpatch = driver.driver.find_elements_by_xpath(inputXpatch)
    for i in inputXpatch:
        try:
            i.clear()
            i.send_keys(input)
        except:
            continue
def automaticSelection(clickElement, option='2',textarea='12',input='12'):
    '''
    评分卡内输入框及选择框自动选择
    参数
        @clickElement：评分卡的表单xpath元素到tbody标签
        @option：下拉框索要选择的位置；            DefaultValue:默认选择第二个
        @textarea：textarea标签输入框输入的内容;   DefaultValue:任意文本值
        @input：input标签输入框输入的内容;         DefaultValue:任意文本值
    '''
    TbodySelect(clickElement, option)
    TbodyInput(clickElement,input)
    TbodyTextarea(clickElement,textarea)

def  inspection_Element(Element):
    element = driver.getElementByAttribute(Element).getText()
    return element

def tally_value(Element,time=20):
    timeout = 0
    element = None
    while timeout < time :
        element = driver.getElementByAttribute(Element).getAttributeText()
        if element == '':
            timeout += 1
            sleep(1)
            continue
        else:
            break
    return element

if __name__ == '__main__':
    login('1001','1')

